package mtblreader;

import java.util.List;

import mtbldomain.MetricDescriptionType;
import mtbldomain.MetricType;
import reader.Converter;
import domain.DomainFactory;
import domain.Entity;
import domain.Metric;
import domain.SystemHistory;
import domain.SystemVersion;

public class MtblConverter implements Converter<List<ProjectDetail>>{
	
	public SystemHistory convert(List<ProjectDetail> projectDetailList) {
		SystemHistory systemHistory = DomainFactory.eINSTANCE.createSystemHistory();
		
		for (ProjectDetail projectDetail : projectDetailList) {
			SystemVersion systemVersion = DomainFactory.eINSTANCE.createSystemVersion();
			systemVersion.setRevisionNumber(projectDetail.getRevisionNumber());
			
			MetricDescriptionType metricDescriptionType = projectDetail.getMetricDescriptionType();
			
			Entity entity = convertMetricDescriptionTypeToEntity(metricDescriptionType);
			entity.setRevisionNumber(systemVersion.getRevisionNumber());
			systemVersion.getEntity().add(entity);
			
			systemHistory.getSystemVersion().add(systemVersion);
		}
		
		
		return systemHistory;
	}
	
	private Entity convertMetricDescriptionTypeToEntity(
			MetricDescriptionType metricDescriptionType) {
		Entity entity = DomainFactory.eINSTANCE.createEntity();

		entity.setFullQualifiedName(metricDescriptionType.getFqname());
		entity.setKind(metricDescriptionType.getKind());
		entity.setContainerName(metricDescriptionType.getContainerName());
		entity.setLocation(metricDescriptionType.getLocation());
		entity.setName(metricDescriptionType.getName());

		for (MetricType metricResult : metricDescriptionType.getMetric()) {
			Metric metric = DomainFactory.eINSTANCE.createMetric();
			metric.setShortName(metricResult.getName());
			metric.setValue(new Double(metricResult.getValue()));
			entity.getMetric().add(metric);
		}

		// se existem filhos
		if (!metricDescriptionType.getMetricDescription().isEmpty()) {
			for (MetricDescriptionType metricDescriptionTypeChild : metricDescriptionType.getMetricDescription()) {
				
				entity.getEntity().add(convertMetricDescriptionTypeToEntity(metricDescriptionTypeChild));
				for (Entity entityChild : entity.getEntity()) {
					entityChild.setParent(entity);
				}
			}
		}
		return entity;
	}

}
